package rand

import (
	"crypto/md5"
	"fmt"
	"math/rand"
	"shop-common/utils/crypto"
	"strconv"
	"time"
)

const DefaultCharset = alphanumeric + "!%@#"

// RandString 产生随机字符串，可用于密码等
func RandString(n int, defaultCharsets ...string) string {
	charset := DefaultCharset
	if len(defaultCharsets) > 0 {
		charset = defaultCharsets[0]
	}

	result, err := String(n, charset)
	if err != nil {
		return crypto.Md5(strconv.Itoa(rand.Intn(999999)))
	}

	return result
}

func Krand(size int, kind int) string {
	ikind, kinds, result := kind, [][]int{[]int{10, 48}, []int{26, 97}, []int{26, 65}}, make([]byte, size)
	is_all := kind > 2 || kind < 0
	rand.Seed(time.Now().UnixNano())
	for i := 0; i < size; i++ {
		if is_all {
			ikind = rand.Intn(3)
		}
		scope, base := kinds[ikind][0], kinds[ikind][1]
		result[i] = uint8(base + rand.Intn(scope))
	}
	return string(result)
}

func KrandNum(size int) string {
	return Krand(size, 0)
}

func KrandLowerChar(size int) string {
	return Krand(size, 1)
}

func KrandUpperChar(size int) string {
	return Krand(size, 2)
}

func KrandAll(size int) string {
	return Krand(size, 3)
}

//生成随机字符串
var _bytes = []byte("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
var r *rand.Rand

// GetRandomString 生成随机字符串
func GetRandomString(n int) string {
	result := []byte{}
	if r == nil {
		r = rand.New(rand.NewSource(time.Now().UnixNano()))
	}

	for i := 0; i < n; i++ {
		result = append(result, _bytes[r.Intn(len(_bytes))])
	}
	return string(result)
}

// GenerateRangeNumString 生成随机数字字符串
func GenerateRangeNumString(n int) string {
	var _bytes = []byte("abcdefghijklmnopqrstuvwxyz0123456789")
	var r *rand.Rand

	result := []byte{}
	if r == nil {
		r = rand.New(rand.NewSource(time.Now().UnixNano()))
	}

	for i := 0; i < n; i++ {
		result = append(result, _bytes[r.Intn(len(_bytes))])
	}
	return string(result)
}

// GenerateRangeNum 生成随机整数 digit：位数
func GenerateRangeNum(digit int) int {
	var max, min int = 1, 1
	if digit > 0 {
		for i := 0; i < digit; i++ {
			max = max * 10
		}
		for i := 0; i < digit-1; i++ {
			min = min * 10
		}
	}
	rand.Seed(time.Now().Unix())
	return rand.Intn(max-min) + min
}

// GetRandInt 生成随机整数 digit：位数
func GetRandInt(min int, max int) int {
	if min > max {
		min = 0
		max = 0
	}
	rand.Seed(time.Now().Unix())
	return rand.Intn(max-min) + min
}

func EncryptRedisKey(dynamicKey string) string {
	if len(dynamicKey) > 32 {
		m := md5.New()
		m.Write([]byte(dynamicKey))
		dynamicKey = fmt.Sprintf("%x", m.Sum(nil))
	}
	return dynamicKey
}
